// 将极客时间专栏文章内容保存为PDF和html文件
(async () => {
  const libHtml2Canvas = chrome.runtime.getURL("lib/html2canvas.min.js");
  const libJsPdf = chrome.runtime.getURL("lib/jspdf.umd.min.js");
  await import(libHtml2Canvas);
  await import(libJsPdf);

  // 引入 jsPDF 和 html2canvas
  const { jsPDF } = window.jspdf;

  const container = document.getElementById('article-content-container');
  if (!container) {
    alert('未找到目标 HTML 元素');
    return;
  }
  const titleElement = container.getElementsByTagName('h1')[0];
  const title = titleElement?.innerText;

  const fileName = `极客时间-${title}`;

  async function downloadPDF(fileName, container) {
    const pdf = new jsPDF('p', 'mm', 'a4'); // A4 尺寸的 PDF
    const pageWidth = 210; // A4 页面宽度（mm）
    const pageHeight = 297; // A4 页面高度（mm）
    const margin = 10; // 边距（mm）

    // 使用 html2canvas 渲染元素为图像
    const canvas = await html2canvas(container, {
      scale: 3, // 提高分辨率
      useCORS: true, // 跨域支持
    });

    const canvasWidth = canvas.width;
    const canvasHeight = canvas.height;

    // 计算 PDF 的宽高比，用于缩放 Canvas 内容
    const pdfScale = (pageWidth - margin * 2) / canvasWidth;

    // 单页高度（像素）
    const singlePageHeightInPx = pageHeight / pdfScale;

    // 当前内容超出单页时，计算分页
    let remainingHeight = canvasHeight;
    let positionY = 0;

    while (remainingHeight > 0) {
      // 添加当前页面内容
      const canvasPage = document.createElement('canvas');
      canvasPage.width = canvas.width;
      canvasPage.height = Math.min(singlePageHeightInPx, remainingHeight);

      const ctx = canvasPage.getContext('2d');
      ctx.drawImage(
        canvas,
        0,
        positionY,
        canvas.width,
        canvasPage.height,
        0,
        0,
        canvas.width,
        canvasPage.height
      );

      const imgData = canvasPage.toDataURL('image/png');

      // 在 PDF 中绘制当前页面
      pdf.addImage(
        imgData,
        'PNG',
        margin,
        0,
        pageWidth - margin * 2,
        (canvasPage.height / canvasPage.width) * (pageWidth - margin * 2)
      );

      // 如果有剩余高度，添加新页面
      remainingHeight -= singlePageHeightInPx;
      positionY += singlePageHeightInPx;

      if (remainingHeight > 0) {
        pdf.addPage();
      }
    }

    // 下载 PDF
    pdf.save(`${fileName}.pdf`);
  }

  function downloadHTML(fileName, container) {
    // const articleContent = container.querySelector('[data-slate-editor="true"]');
    const articleContent = container;
  
    // 包装为完整的 HTML 文件内容
    const fullHTML = `
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>${fileName}</title>
        <link rel="stylesheet" href="${fileName}.css">
        <style>
        html {
          background: #efe8d2;
        }
        body {
          width: 800px;
          margin: 0 auto;
          background: #fbf5ee;
          padding: 20px 20px;
        }
        </style>
      </head>
      <body>
        ${articleContent.outerHTML}
      </body>
      </html>
    `;
    // 创建 Blob 对象
    const htmlBlob = new Blob([fullHTML], { type: 'text/html' });
    
    // 创建一个下载链接
    const htmlLink = document.createElement('a');
    htmlLink.href = URL.createObjectURL(htmlBlob);
    htmlLink.download = `${fileName}.html`;
  
    // 自动触发下载
    document.body.appendChild(htmlLink);
    htmlLink.click();
    document.body.removeChild(htmlLink);

    const styleElements = document.querySelectorAll('style');
    let cssContent = '';

    styleElements.forEach((styleElement) => {
      cssContent += styleElement.textContent + '\n';
    });

    // 创建并下载 CSS 文件
    const blob = new Blob([cssContent], { type: 'text/css' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName + '.css';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  downloadPDF(fileName, container);
  downloadHTML(fileName, container);
})();
